package heartbeat_job

import (
	"common-api/logs"
	"common-api/message"
	"common-api/serialization"
	"common-api/session"
	"sync"
	"time"
)

var UserHeartBeatJobMap sync.Map

var timer = time.NewTicker(5 * time.Second)

func CreateHeartBeatJob(user string, session *session.Session) {
	UserHeartBeatJobMap.Store(user, session)
}
func RemoveHeartBeatJob(user string) {
	UserHeartBeatJobMap.Delete(user)
}

/*func doHeartBeatJob() {
	UserHeartBeatJobMap.Range(func(username, userSession interface{}) bool {
		SendHeartBeatData(username.(string), userSession.(*session.Session))
		return true // 返回 true 继续遍历
	})
}*/

func SendHeartBeatData(username string, s *session.Session) {
	logs.Logger.Debugf("user:%s start send HeartBeatData...", username)
	data := message.HeartBeatReqData{Username: username}
	err, bytes := serialization.JsonEncode(data)
	if err != nil {
		logs.Logger.Errorf("message HeartBeatReq Data encode: %v", err)
		return
	}
	s.WriteMessage(&message.HeaderMessage{
		Type: message.RequestType,
		Code: message.HeartRequestBeatCode,
		Body: bytes,
	})
}

/*func init() {
	// 设置一个 5 秒的定时器
	go func() {
		for {
			select {
			case <-timer.C:
				// 等待定时器触发
				doHeartBeatJob() // 执行定时任务
			}
		}
	}()
}*/
